<template>
  <a-form :form="form" :label-col="{ span: 10 }" :wrapper-col="{ span: 5 }" @submit="handleSubmit">
    <a-form-item label="邮箱">
      <a-input
        placeholder="请输入邮箱地址"
        autocomplete="email"
        v-decorator="[
          'email',
          {
            rules: [
              { required: true, message: '请输入邮箱地址' },
              { type: 'email', message: '请输入有效的邮箱地址' },
              ,
              { validateTrigger: 'blur' }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-row type="flex" :gutter="16">
      <a-col class="gutter-row" :span="16" push="10">
        <a-form-item>
          <a-input
            autocomplete="on"
            size="large"
            type="text"
            :placeholder="$t('user.login.mobile.verification-code.placeholder')"
            v-decorator="[
              'code',
              {
                rules: [{ required: true, message: $t('user.verification-code.required') }],
                validateTrigger: 'blur'
              }
            ]"
          >
            <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
        </a-form-item>
      </a-col>
      <a-col class="gutter-row" :span="8" pull="2">
        <a-button
          class="getCaptcha"
          size="large"
          tabindex="-1"
          :disabled="state.smsSendBtn"
          @click.stop.prevent="getCaptcha"
          v-text="(!state.smsSendBtn && $t('user.register.get-verification-code')) || state.time + ' s'"
        ></a-button>
      </a-col>
    </a-row>
    <a-form-item label="密码">
      <a-input-password
        autocomplete="current-password"
        placeholder="请输入密码"
        type="password"
        v-decorator="[
          'password',
          {
            rules: [{ required: true, message: '请输入密码' }, { validateTrigger: 'blur' }]
          }
        ]"
      />
    </a-form-item>
    <a-form-item label="确认密码">
      <a-input-password
        autocomplete="new-password"
        placeholder="请再次输入密码"
        type="password"
        v-decorator="[
          'repassword',
          {
            rules: [
              { required: true, message: '请再次输入密码' },
              { validator: this.checkPassword, validateTrigger: 'blur' }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 5, offset: 11 }">
      <a-button type="primary" html-type="submit">提交</a-button>
      <a-button :style="{ marginLeft: '8px' }" @click="goback"> 返回 </a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import { getSmsEmail, updatePwd } from '@/api/login'
export default {
  data() {
    return {
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'passwords' }),
      state: {
        time: 60,
        level: 0,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      registerBtn: false
    }
  },
  methods: {
    goback() {
      this.$router.push({ name: 'login' })
    },
    checkPassword(rule, value, callback) {
      const { password } = this.form.getFieldsValue() // 获取密码字段值
      if (value && value !== password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback() // 验证通过
      }
    },
    getCaptcha(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        $message,
        $notification
      } = this

      validateFields(['email'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = $message.loading('验证码发送中..', 0)

          getSmsEmail({ email: values.email })
            .then((res) => {
              setTimeout(hide, 500)
              if (res.code === 200) {
                $notification['success']({
                  message: '提示',
                  description: '验证码为：' + res.result,
                  duration: 3
                })
                // $notification['success']({
                //   message: '提示',
                //   description: '验证码发送成功,请查收~',
                //   duration: 3
                // })
              }
            })
            .catch((err) => {
              console.log(err)

              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              // this.requestFailed(err)
            })
        }
      })
    },
    removeSpacesFromObject(obj) {
      const newObj = {}
      Object.keys(obj).forEach((key) => {
        newObj[key] = obj[key].replace(/\s+/g, '') // 去除所有空格
      })
      return newObj
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)

          updatePwd(this.removeSpacesFromObject(values)).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.result)
            } else {
              this.$message.error(res.message)
            }

            // this.$router.push({ name: 'login' })
          })
          // this.$router.push({ name: 'login' })
        }
      })
    },
    handleSelectChange(value) {
      console.log(value)
      this.form.setFieldsValue({
        note: `Hi, ${value === 'male' ? 'man' : 'lady'}!`
      })
    }
  }
}
</script>

<style scoped></style>
